#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function exec(command, options = {}) {
  try {
    log(`执行命令: ${command}`, 'cyan');
    execSync(command, { 
      stdio: 'inherit', 
      shell: true,
      ...options 
    });
    return true;
  } catch (error) {
    log(`命令执行失败: ${command}`, 'red');
    return false;
  }
}

function checkDependencies() {
  log('检查依赖...', 'yellow');
  
  const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
  const requiredDeps = ['electron', 'electron-builder', 'vite'];
  
  for (const dep of requiredDeps) {
    if (!packageJson.devDependencies[dep]) {
      log(`缺少依赖: ${dep}`, 'red');
      return false;
    }
  }
  
  log('依赖检查完成', 'green');
  return true;
}

function cleanBuild() {
  log('清理构建目录...', 'yellow');
  
  const dirsToClean = ['dist', 'build'];
  for (const dir of dirsToClean) {
    if (fs.existsSync(dir)) {
      fs.rmSync(dir, { recursive: true, force: true });
      log(`已删除目录: ${dir}`, 'green');
    }
  }
}

function buildFrontend() {
  log('构建前端...', 'yellow');
  
  if (!exec('npm run build:frontend')) {
    log('前端构建失败', 'red');
    return false;
  }
  
  log('前端构建完成', 'green');
  return true;
}

function buildElectron() {
  log('构建Electron应用...', 'yellow');
  
  const platform = process.argv[2] || 'all';
  let command = 'npm run build:electron';
  
  switch (platform) {
    case 'win':
      command = 'npm run build:win';
      break;
    case 'mac':
      command = 'npm run build:mac';
      break;
    case 'linux':
      command = 'npm run build:linux';
      break;
    case 'all':
      command = 'npm run build:all';
      break;
    default:
      log(`未知平台: ${platform}，使用默认构建`, 'yellow');
  }
  
  if (!exec(command)) {
    log('Electron构建失败', 'red');
    return false;
  }
  
  log('Electron构建完成', 'green');
  return true;
}

function generateIcons() {
  log('生成应用图标...', 'yellow');
  
  // 这里可以添加图标转换逻辑
  // 可以使用sharp或其他工具将SVG转换为ICO、ICNS、PNG等格式
  log('图标生成完成（需要手动转换SVG为相应格式）', 'green');
}

function main() {
  log('🚀 开始一键打包 M3U8 Downloader', 'bright');
  log('================================', 'cyan');
  
  // 检查依赖
  if (!checkDependencies()) {
    log('❌ 依赖检查失败，请先安装所需依赖', 'red');
    process.exit(1);
  }
  
  // 清理构建目录
  cleanBuild();
  
  // 生成图标
  generateIcons();
  
  // 构建前端
  if (!buildFrontend()) {
    log('❌ 前端构建失败', 'red');
    process.exit(1);
  }
  
  // 构建Electron
  if (!buildElectron()) {
    log('❌ Electron构建失败', 'red');
    process.exit(1);
  }
  
  log('================================', 'cyan');
  log('✅ 打包完成！', 'bright');
  log('构建输出目录: build/', 'green');
  log('可以运行以下命令查看构建结果:', 'yellow');
  log('  npm run pack    # 打包为可执行文件', 'cyan');
  log('  npm run dist    # 构建安装包', 'cyan');
}

// 运行主函数
main();
